package com.horizon.config;

import com.horizon.pojo.IdWorkConf;
import com.horizon.pojo.IdWorkerBuilder;
import com.horizon.service.ConfigureDbService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

/**
 * 初始化数据
 *
 * @author horizon
 */
@Component
public class InitDataListener implements InitializingBean, ServletContextAware {

	private static final Logger logger = LoggerFactory.getLogger(InitDataListener.class);

	@Value("${server.port}")
	private String serverPort;

	@Value("${spring.application.name}")
	private String applicationName;

	@Value("${simple.ip}")
	private String serverIp;

	@Value("${simple.datacenterId}")
	private long datacenterId;

	@Value("${simple.twepoch}")
	private long twepoch;

	@Resource
	private ConfigureDbService configureDbService;

	@Override
	public void afterPropertiesSet() {
	}

	@Override
	public void setServletContext(ServletContext application) {
		IdWorkConf idWorkConf = new IdWorkConf();
		idWorkConf.setServerIp(serverIp);
		idWorkConf.setServerPort(serverPort);
		idWorkConf.setApplicationName(applicationName);
		idWorkConf.setDataCenterId(datacenterId);
		long workerId = configureDbService.initCenterIdWorkId(idWorkConf);
		try {
			IdWorkerBuilder.ID_WORKER.build(twepoch, workerId, datacenterId);
		} catch (Exception e) {
			logger.error("设置IdWorker出错" + e.getCause(), e);
			throw new RuntimeException(e);
		}
	}

}
